/**************************************************************************
 *
 * Copyright (C) 2007 University of California, Los Angeles.
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 *
 *************************************************************************/

package edu.ucla.cs.typecast.net;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.net.SocketException;
import java.net.SocketTimeoutException;

import edu.ucla.cs.typecast.bloomfilter.BloomFilter;

/**
 * This class is an abstraction of network layer which listens to a UDP end point 
 * and dispatches the incoming UDP packet to the upper layer. 
 *
 */
public abstract class AbstractUDPEndPointListener implements EndPointListener, Runnable, TypeCastConstants {

	private TypeCastDispatcher dispatcher; 
	private boolean isActive = false; 
	private DatagramSocket socket; 
	private LBFNotifier lbfNotifier = new LBFNotifier(); 
	private EndPoint activeEndPoint; 
	
	/**
	 * @param dispatcher The the object that dispatches the network packet to upper layer application. 
	 */
	public void setTypeCastDispatcher(TypeCastDispatcher dispatcher) { 
		this.dispatcher = dispatcher; 
	}
	
	
	/**
	 * Activate an endpoint so that it can receive the incoming network packets.
	 * 
	 * @param endPoint The end pont that should be activated.
	 */

	public synchronized  EndPoint activate(EndPoint endPoint) throws IOException {
		if(isActive) { 
			return this.activeEndPoint; 
		}
		socket = createSocket(endPoint); 
		activeEndPoint = new EndPoint(socket.getLocalAddress(), socket.getLocalPort()); 
		isActive = true; 		
		Thread thread = createThread(); 
		thread.start(); 
		return this.activeEndPoint; 
	}
	
	protected Thread createThread() { 
		return new Thread(this); 
	}

	/**
	 * Deactivate a network end point so that it does not receive any 
	 * incoming network packets. 
	 * 
	 * @param endPoint The network end point that should be deactivated. 
	 */
	public void deactivate(EndPoint endPoint) throws IOException{ 
		if(!isActive) { 
			return; 
		}
		isActive = false; 		
		shutdownSocket(socket, endPoint); 
	}

	public EndPoint getEndPoint() { 
		return this.activeEndPoint; 
	}
	
	/**
	 * Update the Local Bloom Filter associated with a specific network
	 * network
	 * 
	 * @param endPoint 
	 * @param LBF The Local Bloom filter to be updated. 
	 */
	
	public void update(EndPoint endPoint, BloomFilter LBF) throws IOException {
		lbfNotifier.updateLBF(endPoint, LBF); 
	}
	
	public boolean isActive() { 
		return isActive; 
	}

	abstract protected DatagramSocket createSocket(EndPoint endpoint) throws IOException; 

	abstract protected void shutdownSocket(DatagramSocket socket, EndPoint endPoint) throws IOException; 

	
	public void run() { 
		while (isActive) {
			try {
				DatagramPacket receivePacket = new DatagramPacket(new byte[MAX_UDP_DATA_LENGTH], MAX_UDP_DATA_LENGTH);
				receivePacket.setLength(MAX_UDP_DATA_LENGTH);
				try {
					socket.receive(receivePacket);
					//System.err.println("Received packet: " + receivePacket);
				} catch (SocketTimeoutException e) {
					// Time out, continue to listen
					e.printStackTrace(); 
					continue;
				} catch (SocketException e) {
					// Socket Closed, continue to listen
					//e.printStackTrace(); 
					return;
				} catch (Throwable t) {
					t.printStackTrace();
					continue; 
				}

				ByteArrayInputStream byteIn = new ByteArrayInputStream(receivePacket.getData(), receivePacket.getOffset(), receivePacket
						.getLength());
				try { 
					EndPoint source = new EndPoint(((InetSocketAddress)receivePacket.getSocketAddress()).getAddress(), ((InetSocketAddress)receivePacket.getSocketAddress()).getPort()); 
					EndPoint target = new EndPoint(receivePacket.getAddress(), socket.getLocalPort()); 
					BloomFilter filter = new BloomFilter();
					filter.readFromStream(byteIn); 
					TransportContext context = new TransportContext(source, target, filter); 
					dispatcher.dispatch(context, byteIn); 
				} catch(Throwable t) { 
					t.printStackTrace(); 
					System.out.println("packet size=" + receivePacket.getLength()); 
				}
			} catch(Throwable t) { 
				t.printStackTrace(); 
			}
		}
	}	

}
